package com.tang;

import com.tang.config.NettyConfig;
import com.tang.server.NettyServer;
import io.netty.channel.ChannelFuture;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.net.InetSocketAddress;

@SpringBootApplication
@RequiredArgsConstructor
public class NettyApplication implements CommandLineRunner {

    private final NettyServer nettyServer;
    private final NettyConfig nettyConfig;

    public static void main(String[] args) {
        SpringApplication.run(NettyApplication.class, args);
    }

    @Override
    public void run(String... args) {
        // 初始化netty服务
        InetSocketAddress inetSocketAddress = new InetSocketAddress(nettyConfig.getHost(), nettyConfig.getPort());
        ChannelFuture channelFuture = nettyServer.bing(inetSocketAddress);
        // 服务停止时销毁netty服务，经过测试，该方法在强制关闭时一样会执行，SpringBoot的销毁方法在强制关闭时不会执行
        Runtime.getRuntime().addShutdownHook(new Thread(nettyServer::destroy));
        channelFuture.channel().closeFuture().syncUninterruptibly();
    }

}
